﻿//------------------------------------------------------------------------------
// System Name:    Customer Service Platform
// Component:      Customer Search Page
// Created By:     Tingrong Shi (trshi@wicresoft.com)
// Created Date:   2011-2-14
//------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ASBCC.Business;
using ASBCC.Business.CIS;
using ASBCC.Database.EntityFramework;

namespace BEGDC.CC.Web.CIS2.Domestic.Search
{
    public partial class CustomerSearch : PagedPage
    {
        //搜索条件
        protected static string Search = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            this.edsCustomer.Where = Search;

            if (!this.IsPostBack)
            {
                Bind();
                Search = firstbound();
                this.edsCustomer.Where = Search;
                this.edsCustomer.DataBind();
                GVCustomer.Visible = true;
                UserRoles userrole = CompanyInfoHelper.GetUserRightByRoleIDs((this.User as CSPrincipal).Role2s);
                if (!userrole.IsDomesticAdmin && !userrole.IsOverseaAdmin)
                {
                    this.btnExport.Visible = false;
                    this.btnExportEmail.Visible = false;
                }
            }
        }

        private string firstbound()
        {
            UserRoles userRoles = CompanyInfoHelper.GetUserRightByRoleIDs((this.User as CSPrincipal).Role2s);
            string roles = (User as CSPrincipal).Role2String;
            string customerWhere = "!it.Disabled and !it.IsDraft and (it.CheckFlag is null or it.CheckFlag==0) ";
            customerWhere += "and ( (Count( select value pc.Province.ProvinceID from it.Company.PCATs as pc where !it.Company.Disabled and !pc.Province.Disabled and !pc.Category.Disabled and ";
            customerWhere += string.Format("Count( select value r.RoleID from pc.Roles as r where !r.Disabled and r.RoleID in {{{0}}} ) > 0 ) > 0", roles);
            customerWhere += " or Count( select value cu.CountryID from it.Company.Countries as cu where !it.Company.Disabled and !cu.Disabled and ";
            customerWhere += string.Format("Count( select value r.RoleID from cu.Roles as r where !r.Disabled and r.RoleID in {{{0}}} ) > 0 ) > 0 )", roles);
            if (userRoles.IsDomesticAdmin)
            {
                customerWhere += " or Count( select value pc.Province.ProvinceID from it.Company.PCATs as pc where !it.Company.Disabled and !pc.Province.Disabled and !pc.Category.Disabled ) > 0";
            }
            if (userRoles.IsOverseaAdmin)
            {
                customerWhere += " or Count( select value cu.CountryID from it.Company.Countries as cu where !it.Company.Disabled and !cu.Disabled ) > 0";
            }
            customerWhere += " ) ";
            return customerWhere;

        }

        protected override EntityDataSource EntitySource
        {
            get { return this.edsCustomer; }
        }

        private void Bind()
        {
            // selectlevel
            selectlevel.DataSource = new[] {
                new { Value = 0, Text = "--请选择--", },
                new { Value = 1, Text = "Level1", },
                new { Value = 2, Text = "Level2", },
                new { Value = 3, Text = "Level3", },
                new { Value = 4, Text = "Level4", },
            };
            selectlevel.DataValueField = "Value";
            selectlevel.DataTextField = "Text";
            selectlevel.DataBind();

            //selectProvince
            selectProvince.DataSource = SearchHelper.GetProvinceByRoleIDs((User as CSPrincipal).Role2s, (User as CSPrincipal).Role2String);
            selectProvince.DataValueField = "ProvinceID";
            selectProvince.DataTextField = "Name";
            selectProvince.DataBind();
            selectProvince.Items.Insert(0, new ListItem("--请选择--", "0"));

            //selectCategory
            selectCategory.DataSource = SearchHelper.GetCategoryByRoleIDs((User as CSPrincipal).Role2s, (User as CSPrincipal).Role2String);
            selectCategory.DataValueField = "CateID";
            selectCategory.DataTextField = "Name";
            selectCategory.DataBind();
            selectCategory.Items.Insert(0, new ListItem("--请选择--", "0"));

            //selectCategory
            selectArea.DataSource = SearchHelper.GetAreaByRoleIDs((User as CSPrincipal).Role2s, (User as CSPrincipal).Role2String);
            selectArea.DataValueField = "AreaID";
            selectArea.DataTextField = "Name";
            selectArea.DataBind();
            selectArea.Items.Insert(0, new ListItem("--请选择--", "0"));

            //selectCategory
            selectCountry.DataSource = SearchHelper.GetCountryByRoleIDs((User as CSPrincipal).Role2s, (User as CSPrincipal).Role2String);
            selectCountry.DataValueField = "CountryID";
            selectCountry.DataTextField = "Name";
            selectCountry.DataBind();
            selectCountry.Items.Insert(0, new ListItem("--请选择--", "0"));

            UserRoles userRoles = CompanyInfoHelper.GetUserRightByRoleIDs((this.User as CSPrincipal).Role2s);
            domestic.Visible = false;
            overseas.Visible = false;
            if (userRoles.IsDomesticSales)
                domestic.Visible = true;
            if (userRoles.IsOverseaSales)
                overseas.Visible = true;

            //selectDegree
            selectDegree.DataSource = new[] {
                new { Value = 0, Text = "--请选择--", },
                new { Value = 1, Text = "大专以下", },
                new { Value = 2, Text = "大专", },
                new { Value = 3, Text = "本科", },
                new { Value = 4, Text = "硕士", },
                new { Value = 5, Text = "博士", },
                new { Value = 6, Text = "MBA", },
                new { Value = 7, Text = "EMBA", },
                new { Value = 8, Text = "DBA", },
            };
            selectDegree.DataValueField = "Value";
            selectDegree.DataTextField = "Text";
            selectDegree.DataBind();

        }




        protected string GetPreferencesValue()
        {
            return CustomerManageHelper.GetPreferencesValue();
        }

        protected string GetPreferencesLevel()
        {
            return CustomerManageHelper.GetPreferencesLevel();
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            UserRoles userRoles = CompanyInfoHelper.GetUserRightByRoleIDs((this.User as CSPrincipal).Role2s);
            this.txtCustomerName.Text = PageSafeHelper.SafeText(this.txtCustomerName.Text);
            this.txtCompanyName.Text = PageSafeHelper.SafeText(this.txtCompanyName.Text);
            this.txtTitle.Text = PageSafeHelper.SafeText(this.txtTitle.Text);
            this.txtEdit.Text = PageSafeHelper.SafeText(this.txtEdit.Text);
            this.txtSchool.Text = PageSafeHelper.SafeText(this.txtSchool.Text);
            this.txtOldCompanyName.Text = PageSafeHelper.SafeText(this.txtOldCompanyName.Text);
            this.txtOldTitle.Text = PageSafeHelper.SafeText(this.txtOldTitle.Text);
            string name = this.txtCustomerName.Text;
            string company = this.txtCompanyName.Text;
            string title = this.txtTitle.Text;
            string Creator = this.txtEdit.Text;
            string level = PageSafeHelper.SafeText(this.selectlevel.SelectedValue);
            string province = PageSafeHelper.SafeText(this.Request.Form["selectProvince"]);
            string category = PageSafeHelper.SafeText(this.Request.Form["selectCategory"]);
            string area = PageSafeHelper.SafeText(this.Request.Form["selectArea"]);
            string country = PageSafeHelper.SafeText(this.Request.Form["selectCountry"]);
            string degree = this.selectDegree.SelectedItem.Text;
            string school = this.txtSchool.Text;
            string workExpname = this.txtOldCompanyName.Text;
            string workExptitle = this.txtOldTitle.Text;
            string CustomerWhere = firstbound();

            if (!String.IsNullOrEmpty(name))
                CustomerWhere += " and it.Name like \"%" + name + "%\"";
            if (!String.IsNullOrEmpty(company))
                CustomerWhere += " and it.Company.Name like \"%" + company + "%\"";
            if (!String.IsNullOrEmpty(title))
                CustomerWhere += " and it.Title like \"%" + title + "%\"";
            if (level != "0")
                CustomerWhere += " and it.Level =" + level;
            if (!String.IsNullOrEmpty(Creator))
                CustomerWhere += " and it.CreateBy.NameEN like \"%" + Creator + "%\"";
            if (userRoles.IsDomesticSales)
            {
                if (!String.IsNullOrEmpty(province) && province != "0")
                    CustomerWhere += " and Count(select value pc.ProvinceID from it.Company.PCATs as pc where pc.ProvinceID = " + province + ")>0";
                if (!String.IsNullOrEmpty(category) && category != "0")
                    CustomerWhere += " and Count(select value pc.CateID from it.Company.PCATs as pc where pc.CateID = " + category + ")>0";
            }
            if (userRoles.IsOverseaSales)
            {
                if (!String.IsNullOrEmpty(country) && country != "0")
                    CustomerWhere += " and Count(select value pc.CountryID from it.Company.Countries as pc where pc.CountryID = " + country + ")>0";
                if (!String.IsNullOrEmpty(area) && area != "0")
                    CustomerWhere += " and Count(select value pc.CountryID from it.Company.Countries as pc where Count( select value ar.AreaID from pc.Areas as ar where ar.AreaID=" + area + ")>0)>0";
            }
            if (!String.IsNullOrEmpty(degree) && degree != "--请选择--")
                CustomerWhere += " and Count(select value edu.EducationID from it.Education as edu where edu.Degree=\"" + degree + "\")>0";
            if (!String.IsNullOrEmpty(school))
                CustomerWhere += " and Count(select value edu.EducationID from it.Education as edu where edu.School like \"%" + school + "%\")>0";
            if (!String.IsNullOrEmpty(workExpname))
                CustomerWhere += " and Count(select value work.WorkExperienceID from it.WorkExperience as work where work.CompanyName like \"%" + workExpname + "%\")>0";
            if (!String.IsNullOrEmpty(workExptitle))
                CustomerWhere += " and Count(select value work.WorkExperienceID from it.WorkExperience as work where work.Title like \"%" + workExptitle + "%\")>0";
            Search = CustomerWhere;
            this.edsCustomer.Where = Search;
            this.GVCustomer.Visible = true;
            this.GVCustomer.PageIndex = 0;
        }

        protected void btnClear_Click(object sender, EventArgs e)
        {
            this.txtCompanyName.Text = "";
            this.txtCustomerName.Text = "";
            this.txtEdit.Text = "";
            this.txtOldCompanyName.Text = "";
            this.txtOldTitle.Text = "";
            this.txtSchool.Text = "";
            this.txtTitle.Text = "";
            this.selectCategory.SelectedIndex = 0;
            this.selectProvince.SelectedIndex = 0;
            this.selectlevel.SelectedIndex = 0;
            this.selectDegree.SelectedIndex = 0;
            this.selectArea.SelectedIndex = 0;
            this.selectCountry.SelectedIndex = 0;
            Search = firstbound();
            edsCustomer.Where = Search;
            edsCustomer.DataBind();
            GVCustomer.PageIndex = 0;
        }



        protected IEnumerable GetEducations(object source)
        {
            return from t in source as IEnumerable<Education>
                   select t;
        }

        protected IEnumerable GetFamilyinfos(object source)
        {
            return from t in source as IEnumerable<FamilyInfo>
                   select t;
        }

        protected IEnumerable GetWorkExperiences(object source)
        {
            return from t in source as IEnumerable<WorkExperience>
                   select t;
        }

        protected object EvalX(string expression)
        {
            CheckPageExists();

            var ctd = base.Page.GetDataItem() as ICustomTypeDescriptor;
            if (ctd != null)
            {
                return DataBinder.Eval(ctd.GetPropertyOwner(null), expression);
            }
            else
                return null;
        }

        private void CheckPageExists()
        {
            if (base.Page == null)
            {
                throw new InvalidOperationException("TemplateControl_DataBindingRequiresPage");
            }
        }

        /// <summary>
        /// 通过customerID取Gender
        /// </summary>
        protected string GetGender(object gender)
        {
            if (gender == null)
                return "";
            if (Convert.ToBoolean(gender) == true)
                return "Male";
            if (Convert.ToBoolean(gender) == false)
                return "Female";
            return "";
        }


        public override void VerifyRenderingInServerForm(System.Web.UI.Control control)
        {
            //base.VerifyRenderingInServerForm(control);
        }
        protected void btnExport_Click(object sender, EventArgs e)
        {
            //HttpContext.Current.Response.Charset = "UTF-8";
            //HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
            //HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("MyCustomer.xls", Encoding.UTF8).ToString());
            //HttpContext.Current.Response.ContentType = "application/ms-excel";
            //this.GVExport.Visible = true;
            //this.GVExport.AllowPaging = false;
            //this.GVExport.AllowSorting = false;
            //this.GVExport.DataBind();
            //System.IO.StringWriter tw = new System.IO.StringWriter();
            //HtmlTextWriter hw = new HtmlTextWriter(tw);
            //this.GVExport.RenderControl(hw);
            //HttpContext.Current.Response.Write(tw.ToString());
            //HttpContext.Current.Response.End();
            //this.GVExport.Visible = false;
            BEGDC.CC.Web.Control.ExportDataGridToExcel.Export(this.Page, this.GVExport, "CustomerList.xls");
        }

        protected void btnExportEmail_Click(object sender, EventArgs e)
        {
            /*
            HttpContext.Current.Response.Charset = "UTF-8";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("CustomerEmailList.xls", Encoding.UTF8).ToString());
            HttpContext.Current.Response.ContentType = "application/ms-excel";
            this.GVExportEmail.Visible = true;
            this.GVExportEmail.AllowPaging = false;
            this.GVExportEmail.AllowSorting = false;
            this.GVExportEmail.DataBind();
            System.IO.StringWriter tw = new System.IO.StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(tw);
            this.GVExportEmail.RenderControl(hw);
            HttpContext.Current.Response.Write(tw.ToString());
            HttpContext.Current.Response.End();
            this.GVExportEmail.Visible = false;
             * */

            BEGDC.CC.Web.Control.ExportDataGridToExcel.Export(this.Page, this.GVExportEmail, "CustomerEmailList.xls");


        }
        protected string GetUserType()
        {
            UserRoles userRoles = CompanyInfoHelper.GetUserRightByRoleIDs((this.User as CSPrincipal).Role2s);
            if (userRoles.IsDomesticSales)
                return "dom";
            else
                return "ove";
        }

        protected string GetCil()
        {
            return (User as CSPrincipal).CIL;
        }

    }
}
